<template>
  <form class="form-horizontal" method="post" id="id_post_form" v-on:submit.prevent="submit(0)" v-if="is_show">
    <div class="node" v-for="node in nodes" :key="node.id">
      <h4>{{ node.title }}</h4>
      <input type="hidden" name="node" :value="node.id">

      <template v-if="node.action_type === 1 || node.action_type === 4">
        <!-- {#单选/判断#} -->
        <div>
          <ul v-for="(child,idx) in node.items" class="no-bd" :key="'key-'+idx">
            <div radio :value="child.id" :title="child.title" @change="radio_checked(node, child, $event)" :checked="child.checked ? true : false" v-model="child.checked">
            </div>
            <input-widget input_style="2" v-on:add_item="add_item" :node="child" :parent_node="node" v-on:update="input_complete" v-if="child.checked" v-on:on_keyup="on_keyup" />
          </ul>
        </div>

      </template>

      <template v-else-if="node.action_type === 2">
        <!-- {#多选#} -->
        <div>
          <div v-for="(child,idx) in node.items" checkbox :value="child.id" :title="child.title" :key="'key-'+idx" @change="checkbox_checked(node, child, $event)" :checked="child.checked ? true : false" v-model="child.checked"></div>
        </div>
      </template>

      <template v-else-if="node.action_type === 5">
        <!-- {#多填#} -->
        <div>
          <!-- Text Input -->
          <div v-for="(child,idx) in node.items" :key="'key-'+idx">
            <div>{{child.title}}</div>
            <input-widget input_style="1" v-on:add_item="add_item" :node="child" :parent_node="node" v-on:update="input_complete" v-on:on_keyup="on_keyup" />
          </div>
        </div>
      </template>

      <template v-else-if="node.action_type === 3">
        <!-- {#单填#} -->

        <input-widget v-on:add_item="add_item" :node="node" :parent_node="node" v-on:update="input_complete" v-on:on_keyup="on_keyup" />
      </template>

    </div>
    <div class="content-block" v-if="nodes.length">
      <a href="#" class="button button-big button-fill Submint-Button" v-if="is_show_submit_btn" v-on:click.stop.prevent="submit(1, $event)">提交保存</a>
    </div>
  </form>
</template>

<script>
/* eslint-disable no-new */
import input_widget from './FMobileInputWidget.vue'
import Area_data from '../datas/area_data'
import $jquery from 'jquery'

function AscSort(a, b) {
  // 正序排列
  return a.lft - b.lft
}

function getIdCardInfo(cardNoStr) {
  var info = {
    is_valid: false, // 身份证号是否有效。默认为 false
    year: null, // 出生年。默认为null
    month: null, // 出生月。默认为null
    day: null, // 出生日。默认为null
    isMale: false, // 是否为男性。默认false
    area: '', // 地区
    no: ''
  }

  var patt = new RegExp('^s?([0-9xX]{15,18})')
  var ret = patt.exec(cardNoStr)
  if (!ret) {
    return info
  }
  info['no'] = ret[0].toUpperCase()
  var cardNo = info['no']

  if (!cardNo || (cardNo.length !== 15 && cardNo.length !== 18)) {
    info['is_valid'] = false
  }
  var d = Area_data[cardNo.slice(0, 6)]
  var c = Area_data[cardNo.slice(0, 4)]
  var p = Area_data[cardNo.slice(0, 2)]
  if (!d) {
    if (!c) {
      info['area'] = p
    }
    info['area'] = p + c
  } else if (p === c) {
    info['area'] = p + d
  } else {
    info['area'] = p + c + d
  }

  if (cardNo.length === 15) {
    let year = cardNo.substring(6, 8)
    let month = cardNo.substring(8, 10)
    let day = cardNo.substring(10, 12)
    let p = cardNo.substring(14, 15) // 性别位
    let birthday = new Date(year, parseFloat(month) - 1, parseFloat(day))
    // 对于老身份证中的年龄则不需考虑千年虫问题而使用getYear()方法
    if (
      birthday.getYear() !== parseFloat(year) ||
      birthday.getMonth() !== parseFloat(month) - 1 ||
      birthday.getDate() !== parseFloat(day)
    ) {
      info['is_valid'] = false
    } else {
      info['is_valid'] = true
      info.year = birthday.getFullYear()
      info.month = birthday.getMonth() + 1
      info.day = birthday.getDate()
      if (p % 2 === 0) {
        info.isMale = false
      } else {
        info.isMale = true
      }
    }
    return info
  }

  if (cardNo.length === 18) {
    let year = cardNo.substring(6, 10)
    let month = cardNo.substring(10, 12)
    let day = cardNo.substring(12, 14)
    let p = cardNo.substring(14, 17)
    let birthday = new Date(year, parseFloat(month) - 1, parseFloat(day))
    // 这里用getFullYear()获取年份，避免千年虫问题
    if (
      birthday.getFullYear() !== parseFloat(year) ||
      birthday.getMonth() !== parseFloat(month) - 1 ||
      birthday.getDate() !== parseFloat(day)
    ) {
      info['is_valid'] = false
      return info
    }

    var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1] // 加权因子
    var Y = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2] // 身份证验证位值.10代表X

    // 验证校验位
    var sum = 0 // 声明加权求和变量
    var _cardNo = cardNo.split('')

    if (_cardNo[17].toUpperCase() === 'X') {
      _cardNo[17] = 10 // 将最后位为x的验证码替换为10方便后续操作
    }
    for (var i = 0; i < 17; i++) {
      sum += Wi[i] * _cardNo[i] // 加权求和
    }
    var ii = sum % 11 // 得到验证码所位置

    if (_cardNo[17] !== Y[ii]) {
      info['is_valid'] = false
    } else {
      info['is_valid'] = true
    }

    info.year = birthday.getFullYear()
    info.month = birthday.getMonth() + 1
    info.day = birthday.getDate()
    if (p % 2 === 0) {
      info['isMale'] = false
    } else {
      info['isMale'] = true
    }
    return info
  }
  return info
}

export default {
  name: 'data_collect_f',
  props: ['opackage_id', 'ocase_id', 'navTitle'],
  data: function() {
    return {
      nodes: [],
      node_values: {},
      selected: {},
      case_id: '',
      package_id: '',
      is_on_submit: 0,
      is_show_submit_btn: 0,
      last_id: '',
      is_update_selected: 0,
      current_node: ['', ''], // node, 操作类型:'', cancel, force, parent_id
      js_c: '', // 自定义js组件
      st: '', // 提交类型
      is_show: 0, // 是否显示输入
      is_submit_now: 0
    }
  },
  mounted: function() {
    var self = this

    $jquery(window).bind('beforeunload', function() {
      // console.log(self.is_submit_now);
      if (!self.is_submit_now) {
        return '确定离开此页面吗？'
      } else {
      }
    })

    // var s = '',
    //   query = ''

    if (!self.opackage_id) {
      if (this.$route.params.id) {
        var url = 'https://yn.12348.laway.cn/node/next/' + this.$route.params.id
        self.package_id = this.$route.params.id
        var data = { package_id: self.package_id }
      } else {
        return
        // 没解析到做题ID；
      }
    }

    self.last_id = self.package_id
    // console.log('api', '/api' + url + query, data);
    // console.log('url', url)
    $jquery.post(url, data, function(results) {
      self.nodes = results
      self.nodes.sort(AscSort)
      setTimeout(function() {
        results.forEach(function(item) {
          self.selected['q_' + item.id] = item.id
          if (item.items && item.items.length) {
            item.items.forEach(function(child) {
              if (child.checked) {
                self.selected['q_' + child.id] = child.id
              }
            })
          } else if (
            item.action_type === 3 &&
            item.input_type === 29 &&
            item.input_args
          ) {
            self.js_c = item.input_args
          }
        })
        self.is_show_submit_btn = 1
        self.is_show = 1
      }, 0)
    })
  },
  components: {
    'input-widget': input_widget
  },
  watch: {
    opackage_id: function(new_value, old_value) {
      // 一个页面的多次加载
      // console.log(new_value + ' : ' + old_value);
      // console.log(new_value);
      var self = this
      self.package_id = self.opackage_id
      self.case_id = self.ocase_id
      var data = { package_id: self.package_id, case_id: self.case_id }
      var url = 'https://yn.12348.laway.cn/node/next/' + self.package_id
      // if (self.ocase_id) {
      // data['case_id'] = self.case_id;
      // url += '/' + self.case_id
      self.st = 'ec'

      self.is_show = 0
      self.last_id = self.package_id
      $jquery.post(url, data, function(results) {
        self.nodes = results
        // #排序
        self.nodes.sort(AscSort)
        setTimeout(function() {
          results.forEach(function(item) {
            self.selected['q_' + item.id] = item.id
            if (item.items && item.items.length) {
              item.items.forEach(function(child) {
                if (child.checked) {
                  self.selected['q_' + child.id] = child.id
                }
              })
            } else if (
              item.action_type === 3 &&
              item.input_type === 29 &&
              item.input_args
            ) {
              self.js_c = item.input_args
            }
          })
          self.is_show_submit_btn = 1
          self.is_show = 1
        }, 0)
      })
    },
    current_node: function(new_value, old_value) {
      var self = this
      var node = new_value[0]
      // var old_node = old_value[0]
      // 如果是选项
      /*
      第一次选: node 有值， old_node 没有值， 判断node有没有u,有u就更新，没有u就不更新
      第二次选: node 等于cancel, 判断node有没有u
      第三次选: node等于cancel, old_node也等于cancel, cancel类型需要为list, 判断node有没有u
      第四次选: node有值，old_node等于cancel, 就判断node有没有u
      第五次选: node有值，old_node也有值，但是不同的题，就判断node有没有u

      第六次选: node有值，old_node也有值，是同一个题，并且是单选题，就判断node有没有u，也要判断 old_node有没有u
      第7次选: node有值，old_node也有值，是同一个题，并且是多选题，就判断node有没有u
      第八次选: node有值，old_node也有值，有强制更新，就必须更新

      */
      var is_update = 0
      if (new_value[1] === 'force') {
        is_update = 1
      } else if (new_value[0].u) {
        is_update = 1
      }

      // self.get_next_data(node.id);
      if (is_update) {
        self.get_next_data(node.id)
      }
    }
  },
  methods: {
    on_click: function() {
      this.is_click_done = 1
    },

    cancel_select: function(parent_node, current, event) {
      var self = this
      // 如果是取消
      // 隐藏子集子节点数据
      if (self.selected['q_' + current.id]) {
        delete self.selected['q_' + current.id]
      }
      self.current_node = [current, 'cancel']

      if (self.selected['q_' + parent_node.id]) {
        delete self.selected['q_' + parent_node.id]
      }
      current.checked = ''
      self.get_current_selected(parent_node, current)
      self.is_update_selected = 1
    },
    get_input_val: function(node) {
      if (
        node.input_type === 21 &&
        node.input_widget &&
        node.input_widget.action_type === 2
      ) {
        return node.default
      } else if (node.input_type === 23 && node.input_items) {
        var results = []
        node.items.forEach(function(item) {
          var row = []
          var i = 0
          item.forEach(function(field) {
            row.push({ id: node.input_items[i].id, val: field.default })
            i += 1
          })
          results.push(row)
        })
        return results
      } else {
        return [node.default]
      }
    },

    on_keyup: function(e, parent_node, node) {
      var self = this
      // var is_update = 1
      if (self.node_values['q_' + node.id]) {
        if (self.node_values['q_' + node.id] !== node.default) {
          self.node_values['q_' + node.id] = node.default
        }
      } else {
        self.node_values['q_' + node.id] = node.default
      }
      self.selected['q_' + parent_node.id] = node.id

      // self.lazy_input_complete(e, parent_node, node);
    },

    input_complete: function(e, parent_node, node) {
      var self = this
      var is_update = 1
      self.current_node = [node, '']

      /*
      // 固定写死的优化输入插件, 身份证号输入后，自动填写好年龄，姓别，出生年月
      */
      // 咨询接待律师 // 跟案核实案情简介
      if (node.id === '2f29cb1934f42099092772c52bb40de3aa6899d8') {
        // console.log('更新身份证');
        if (node.default.length === 18) {
          var info = getIdCardInfo(node.default)
          var now = new Date()
          var age = now.getFullYear() - info['year']

          var birthday_str =
            now.getFullYear() + '-' + info['month'] + '-' + info['day']
          var birthday = new Date(birthday_str.replace('-', '/'))
          if (now < birthday) {
            age = age - 1
          }

          if (age <= 0) {
            age = 0
          }

          var g = '589fd12b1e22272573d78fc1'
          if (info['isMale']) {
            g = '589fd12b1e22272573d78fc0'
          }

          parent_node.items = parent_node.items.map(function(node_item) {
            if (node_item.id === '9811bb6e89d552aa5d77c0fc8db52cb78f1a8cc9') {
              node_item.default = age
            } else if (
              node_item.id === '6c04a80d33e4603d06221a46b968f81df5a45bd2'
            ) {
              node_item.default = g
            } else if (
              node_item.id === '616387150f34540bd5d70f162f957d715766d513'
            ) {
              node_item.default = info['area']
            }
            return node_item
          })
        }
      }

      self.selected['q_' + parent_node.id] = node.id
      if (is_update) {
        this.update_panel(parent_node, node)
      }
    },
    add_item: function(node, event) {
      var row = []
      var i = {}
      var l = node.items.length
      node.items[0].forEach(function(item) {
        i = {}
        $jquery.extend(i, item)
        i.id = i.id + '_' + l
        i.default = ''
        row.push(i)
      })

      node.items.push(row)
    },
    get_current_selected: function(parent_node, current) {
      var self = this,
        current_selected = {},
        nodes_key = []
      // console.log('get_current_selected', current)
      if (current) {
        self.current_key = current.id
      }
      var nodes = self.nodes.map(function(node_item) {
        if (node_item.action_type === 4 || node_item.action_type === 1) {
          var checked_item = false
          node_item.items.map(function(child_node) {
            // console.log('child_node', child_node)
            if (parent_node && node_item.id === parent_node.id) {
              if (
                current &&
                current.checked &&
                child_node.id === current.checked
              ) {
                checked_item = child_node
                child_node.checked = current.id
              } else {
                child_node.checked = ''
              }
              return child_node
            } else if (child_node.checked) {
              checked_item = child_node
              return child_node
            }
          })

          current_selected[node_item.id] = { t: node_item.title }
          // console.log('1-current_selected', current_selected)
          if (checked_item) {
            if (nodes_key.indexOf(node_item.id) === -1) {
              nodes_key.push(node_item.id)
            }
            // if (checked_item.default) {
            if (checked_item.input_type) {
              current_selected[checked_item.id] = {
                t: checked_item.title,
                val: self.get_input_val(checked_item)
              }
            } else {
              current_selected[checked_item.id] = { t: checked_item.title }
            }
          }
          // console.log('current_selected', current_selected)
        } else if (node_item.action_type === 2) {
          var checked_list = []
          node_item.items.forEach(function(child_node) {
            if (child_node.checked) {
              checked_list.push(child_node.id)
              if (
                child_node.default ||
                (current &&
                  child_node.id === current.id &&
                  child_node.default === '')
              ) {
                current_selected[child_node.id] = {
                  t: child_node.title,
                  val: self.get_input_val(child_node)
                }
              } else {
                current_selected[child_node.id] = { t: child_node.title }
              }
            }
          })

          current_selected[node_item.id] = { t: node_item.title }
          if (checked_list.length) {
            if (nodes_key.indexOf(node_item.id) === -1) {
              nodes_key.push(node_item.id)
            }
            current_selected[node_item.id] = { t: node_item.title }
          }
        } else if (node_item.action_type === 3) {
          if (
            node_item.action_type === 3 &&
            node_item.input_type === 29 &&
            node_item.input_args
          ) {
            self.js_c = node_item.input_args
            // console.log('node_item.input_args:');
            // console.log(node_item.input_args);
            // console.log(node_item.default);
          }

          current_selected[node_item.id] = {
            t: node_item.title,
            val: self.get_input_val(node_item)
          }
          if (nodes_key.indexOf(node_item.id) === -1) {
            nodes_key.push(node_item.id)
          }
        } else if (node_item.action_type === 5) {
          node_item.items.forEach(function(child_node) {
            current_selected[node_item.id] = { t: node_item.title }

            if (child_node.input_type) {
              current_selected[child_node.id] = {
                t: child_node.title,
                val: self.get_input_val(child_node)
              }
            } else {
              current_selected[child_node.id] = { t: child_node.title }
            }
            if (nodes_key.indexOf(node_item.id) === -1) {
              nodes_key.push(node_item.id)
            }
            // }
          })
        }

        return node_item
      })

      self.nodes = nodes
      self.current_selected = current_selected
      self.nodes_key = nodes_key
    },

    radio_checked: function(node, current, event) {
      // console.log('radio_checked', current)
      current.checked = current.id
      // 如果选择了radio
      // var children = []
      var self = this
      self.on_click()
      var is_update = true
      // 判断是否选择过了,
      var action = ''

      if (!self.selected['q_' + current.id]) {
        // 如果没有选择过
        node.items.forEach(function(item) {
          if (item.id === current.id) {
            self.selected['q_' + node.id] = node.id
            self.selected['q_' + current.id] = current.id
          } else if (self.selected['q_' + item.id]) {
            if (item.u) {
              action = 'force'
            }
            delete self.selected['q_' + item.id]
          }
        })
        self.current_node = [current, action]
      } else {
        // 如果选择过了
        is_update = false
      }

      // 需要更新
      if (is_update) {
        this.$set(current, 'checked', current.id)
        self.get_current_selected(node, current)
        // 获取lft大于当前节点的，可能会引起更新
        // var lt_lfts = []
      }
    },

    checkbox_checked: function(node, child, event) {
      // 如果选择了radio
      // var children = []
      var self = this
      self.on_click()
      var is_update = true
      // 判断是选中还是取消
      // console.log('child.checked',child.checked,child)
      if (child.checked) {
        // 如果是选中
        is_update = true
        self.selected['q_' + node.id] = child.id
        self.selected['q_' + child.id] = child.id
        self.current_node = [child, '']
      } else {
        // 如果是取消
        // 隐藏子集子节点数据
        is_update = true
        // self.selected[event.target.name] = event.target.value;
        // self.selected[child.id] = child.id;
        if (self.selected['q_' + child.id]) {
          delete self.selected['q_' + child.id]
        }
        self.current_node = [child, 'cancel']
      }

      // 需要更新
      if (is_update) {
        this.$set(child, 'checked', child.id)
        self.get_current_selected(node, child)
      }
    },

    // update_panel:function(current_id){
    update_panel: function(parent_node, node) {
      var self = this
      self.get_current_selected(parent_node, node)
    },
    get_next_data: function(current_id) {
      var self = this
      // console.log('ADD:', self.current_selected)
      var d = { package_id: self.package_id, case_id: self.case_id }
      d['c'] = encodeURI(JSON.stringify(self.current_selected))
      d['s'] = self.current_key
      self.last_id = current_id

      self.is_show_submit_btn = 0

      $jquery.post('https://yn.12348.laway.cn/node/next/' + current_id, d, function(
        results
      ) {
        // var new_results = []

        if (self.is_update_selected) {
          self.selected = {}
          self.is_update_selected = 0
          results.forEach(function(item) {
            if (
              item.action_type === 3 &&
              item.input_type === 29 &&
              item.input_args
            ) {
              self.js_c = item.input_args
            }
            self.selected['q_' + item.id] = item.id
            if (item.items && item.items.length) {
              item.items.forEach(function(child) {
                if (child.checked) {
                  self.selected['q_' + child.id] = child.id
                }
              })
            }
          })
        } else {
          results.map(function(item) {
            if (
              item.action_type === 3 &&
              item.input_type === 29 &&
              item.input_args
            ) {
              self.js_c = item.input_args
            }

            if (self.node_values['q_' + item.id]) {
              item.default = self.node_values['q_' + item.id]
            }
            if (self.selected['q_' + item.id] && item.items) {
              item = item.items.map(function(child) {
                if (child.id === self.selected['q_' + child.id]) {
                  child.checked = child.id
                } else {
                  child.checked = ''
                }
                if (self.node_values['q_' + child.id]) {
                  child.default = self.node_values['q_' + child.id]
                }
                return child
              })
            }
            return item
          })
        }
        self.nodes = results

        // #排序
        self.nodes.sort(AscSort)

        self.is_show_submit_btn = 1
      })
    },
    submit: function(state, event) {
      if (!state) {
        return false
      }
      var self = this
      self.is_submit_now = 1
      $jquery('#id_post_form').waitMe({ effect: 'ios', text: '数据提交中...' })
      self.get_current_selected()

      var d = { package_id: self.package_id, case_id: self.case_id }
      d['n'] = JSON.stringify(self.nodes_key)
      d['c'] = encodeURI(JSON.stringify(self.current_selected))

      if (self.is_on_submit) {
        return 0
      }
      self.is_on_submit = 1

      setTimeout(function() {
        self.is_on_submit = 0
      }, 3000)
      var url = '/case/data_add1/' + self.package_id + '/'
      // console.log('data_add1 start')
      $jquery.post(url, d, function(results) {
        if (results.state === 'done') {
          // window.location = results.url;
          self.$f7.mainView.loadPage(results.url + '?title=' + self.navTitle)
          // self.$router.loadPage(results.url)
          $jquery('#id_post_form').waitMe('hide')
        } else {
          $jquery('#id_post_form').waitMe('hide')
          alert(results.error)
        }
        self.is_on_submit = 0
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.testPage {
  .node {
    background: none;
    h4 {
      font-weight: bold;
      font-size: 18px;
    }
    .list-block {
      .item-title {
        font-size: 14px;
      }
    }
    .no-bd {
      &:after {
        display: none;
      }
    }
  }
}
</style>

